import { _decorator, Component, Node, sys, game } from 'cc';
import AdShowHelper from './AdShowHelper';
import EventManagerInstance, { GameMsgType } from './EventManagerInstance';
import { BannerClient } from 'db://admob/ads/client/BannerClient';
import { LoadAdError } from 'db://admob/ads/alias/TypeAlias';
import { BannerSize } from 'db://admob/misc/BannerSize';
import { BannerAlignment, BottomCenter, TopCenter } from 'db://admob/misc/BannerAlignment';
import { BannerPaidEventNTF, InterstitialPaidEventNTF } from 'db://admob/proto/PaidEventNTF';
import { BannerSizeType } from 'db://admob/misc/BannerSizeType';
import { InterstitialAdClient } from 'db://admob/ads/client/InterstitialAdClient';
import { RewardedAdClient } from 'db://admob/ads/client/RewardedAdClient';
import { log } from 'cc';
const { ccclass, property } = _decorator;
export enum PlatformType {
    PLATFORM_TYPE_NONE = 0,
    PLATFORM_TYPE_WEIXIN,
    PLATFORM_TYPE_BYTEDACE,
    PLATFORM_TYPE_KUAISHOU,

    PLATFORM_TYPE_ANDROID,
    PLATFORM_TYPE_IOS,
}
/**
 * Predefined variables
 * Name = AdSDKInstance
 * DateTime = Thu Apr 14 2022 16:48:30 GMT+0800 (中国标准时间)
 * Author = withtea
 * FileBasename = AdSDKInstance.ts
 * FileBasenameNoExtension = AdSDKInstance
 * URL = db://assets/scripts/BaseInstance/AdSDKInstance.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */
export enum GoogleAdmobUnitId {
    BannerAd = 'ca-app-pub-7671481828685849/5805207084',
    InterstitialAd = 'ca-app-pub-7671481828685849/2681152629',
    AppOpenAd = '',
    RewardedAd = 'ca-app-pub-7671481828685849/8017239789',
    NativeAd = '',
    RewardedInterstitialAd = '',
}
const bannermodule = '[AdmobTestBanner]';
const interstmodule = '[AdmobTestInterstitialAdts]';
const rewardmodule = '[AdmobTestRewarded]';
@ccclass('AdSDKInstance')
export default class AdSDKInstance {
    private static instance: AdSDKInstance = null;
    private m_window_width = 0;
    private m_window_height = 0;

    private m_banner_ad = null;
    private m_rewarded_video_ad = null;
    public m_interstitial_ad = null;

    private m_platform_type = 0;
    private m_bannerad_id: string = '';
    private m_interstad_id: string = '';
    private m_rewardad_id: string = '';
    private m_load_interst_ad: boolean = false;
    private m_banner_retry_count = 0;
    private m_cant_ad: boolean = false;
    private m_reward_ad_use: boolean = true;
    private currentAlignment: BannerAlignment[] = BottomCenter;
    private m_google_ad_rewarded: boolean = false;

    private m_android_banner_loaded: boolean = false;
    private m_android_banner_visible: boolean = false;
    public static GetInstance() {
        if (this.instance == null) {
            this.instance = new AdSDKInstance();
            if (sys.platform == sys.Platform.WECHAT_GAME) {
                this.instance.m_bannerad_id = 'adunit-1f543d4a3070b935'; //banner广告
                this.instance.m_interstad_id = 'adunit-75f1f155672db3f5'; //插屏广告
                this.instance.m_rewardad_id = 'adunit-706032848e1a7d0f'; //激励广告
                this.instance.m_cant_ad = false;
                this.instance.m_reward_ad_use = true;
                this.instance.m_platform_type = PlatformType.PLATFORM_TYPE_WEIXIN;
            } else if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
                this.instance.m_platform_type = PlatformType.PLATFORM_TYPE_BYTEDACE;
                this.instance.m_bannerad_id = '5ii5medlmm6b1u00te'; //banner广告
                this.instance.m_interstad_id = '5jcafjkh1j0j2178fb'; //插屏广告
                this.instance.m_rewardad_id = '3bcgci1ji655627fak'; //激励广告
                this.instance.m_cant_ad = false;
                this.instance.m_reward_ad_use = true;
                this.instance.m_banner_retry_count = 5;
            } else if (sys.platform == sys.Platform.IOS) {
                this.instance.m_platform_type = PlatformType.PLATFORM_TYPE_IOS;
            } else if (sys.platform == sys.Platform.ANDROID) {
                this.instance.m_platform_type = PlatformType.PLATFORM_TYPE_ANDROID;
                this.instance.currentAlignment = BottomCenter;
                this.instance.m_google_ad_rewarded = false;
            } else {
                this.instance.m_platform_type = PlatformType.PLATFORM_TYPE_NONE;
            }
        }
        return this.instance;
    }
    public LoadInterstitialAd() {
        if (this.m_interstitial_ad != null) {
            console.log('调用加载插屏广告');
            this.m_interstitial_ad.load();
        }
    }
    public IOSInitAD() {
        if (this.m_cant_ad) {
            return;
        }

        if (this.m_platform_type == PlatformType.PLATFORM_TYPE_IOS) {
            // jsb.reflection.callStaticMethod('CocosPlatformHelper', 'InitAD', '()V');
        }
    }
    public CreateInterstitialAd() {
        if (this.m_cant_ad) {
            return;
        }
        if (this.m_platform_type == PlatformType.PLATFORM_TYPE_WEIXIN) {
            this.m_interstitial_ad = wx.createInterstitialAd({
                adUnitId: this.m_interstad_id,
            });
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_BYTEDACE) {
            this.m_interstitial_ad = tt.createInterstitialAd({
                adUnitId: this.m_interstad_id,
            });
            if (this.m_interstitial_ad != null) {
                this.m_interstitial_ad.onError((err) => {
                    console.log('load插屏广告失败:');
                    console.error(this.SwitchShowErrCode(err.errCode));
                }); // 自动load 的失败会走到这里
                this.m_interstitial_ad.onLoad(() => {
                    console.log('load插屏广告成功');
                }); //创建会自动load
            }
            AdShowHelper.SetAfterTimeToCanShowAD(31);
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_IOS) {
            AdShowHelper.SetAfterTimeToCanShowAD(1);
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_ANDROID) {
            AdShowHelper.SetAfterTimeToCanShowAD(1);
        }
    }
    public GetRewardADuse() {
        return this.m_reward_ad_use;
    }

    public CreateBannerAD() {
        if (this.m_cant_ad) {
            return;
        }
        if (this.m_platform_type == PlatformType.PLATFORM_TYPE_WEIXIN) {
            // 手机屏幕信息
            let winSize = wx.getSystemInfoSync();
            this.m_window_height = winSize.windowHeight;
            this.m_window_width = winSize.windowWidth;
            //创建
            if (this.m_banner_ad == null) {
                this.m_banner_ad = wx.createBannerAd({
                    adUnitId: this.m_bannerad_id,
                    style: {
                        left: this.m_window_width / 2 - 150,
                        top: this.m_window_height - 90,
                        width: 300,
                    },
                });
                this.m_banner_ad.onResize(() => {
                    this.m_banner_ad.style.left = this.m_window_width / 2 - 150 + 0.1;
                    this.m_banner_ad.style.top = this.m_window_height - this.m_banner_ad.style.realHeight + 0.1;
                });
                this.m_banner_ad.onError((err) => {
                    console.error('Banner广告 错误');
                    console.error(this.SwitchShowErrCode(err.errCode));
                    this.m_banner_ad.destroy();
                    this.m_banner_ad = null;
                    this.CreateBannerAD();
                });
            }
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_BYTEDACE) {
            // 手机屏幕信息
            let winSize = tt.getSystemInfoSync();
            this.m_window_height = winSize.windowHeight;
            this.m_window_width = winSize.windowWidth;
            var targetBannerAdWidth = this.m_window_width;
            //创建
            if (this.m_banner_ad == null) {
                this.m_banner_ad = tt.createBannerAd({
                    adUnitId: this.m_bannerad_id,
                    adIntervals: 30,
                    style: {
                        top: this.m_window_height - 40,
                        width: targetBannerAdWidth,
                    },
                });
                // this.m_banner_ad.load();
                this.m_banner_ad.style.left = (this.m_window_width - targetBannerAdWidth) / 2;
                this.m_banner_ad.onResize((size) => {
                    this.m_banner_ad.style.top = this.m_window_height - size.height;
                    this.m_banner_ad.style.left = (this.m_window_width - size.width) / 2;
                });
                this.m_banner_ad.onError((err) => {
                    console.error('Banner广告 错误');
                    console.error(this.SwitchShowErrCode(err.errCode));
                    if (this.m_banner_retry_count > 0) {
                        this.m_banner_retry_count--;
                        this.m_banner_ad.destroy();
                        this.m_banner_ad = null;
                        this.CreateBannerAD();
                    }
                });
            }
        }
    }
    public CreateRewardAd() {
        if (this.m_cant_ad) {
            return;
        }
        if (this.m_platform_type == PlatformType.PLATFORM_TYPE_WEIXIN) {
            this.m_rewarded_video_ad = wx.createRewardedVideoAd({
                adUnitId: this.m_rewardad_id,
            });
            /*
      this.m_rewarded_video_ad.onLoad((res) => {
        console.log(res.shareValue);
        console.log(res.rewardValue);
        if (res.rewardValue == 1) {
          this.m_reward_ad_use = true;
        }
        if (res.shareValue == 1) {
          this.m_reward_ad_use = false;
        }
      });
      */

            this.m_rewarded_video_ad.onError((err) => {
                console.log('激励视频展示失败');
                console.log(err);
            });
            this.m_rewarded_video_ad.onClose((res) => {
                // 用户点击了【关闭广告】按钮
                if ((res && res.isEnded) || res === undefined) {
                    console.log('长激励广告正常播放结束');
                    wx.showToast({
                        title: '激励广告正常播放结束',
                        icon: 'none',
                        duration: 1500,
                    });
                    EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, true);
                } else {
                    console.log('长激励广告播放中途结束');
                    wx.showToast({
                        title: '激励广告播放中途结束',
                        icon: 'none',
                        duration: 1500,
                    });
                    EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, false);
                }
            });
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_BYTEDACE) {
            this.m_rewarded_video_ad = tt.createRewardedVideoAd({
                adUnitId: this.m_rewardad_id,
            });
            this.m_rewarded_video_ad.onError((err) => {
                console.log('激励视频展示失败');
                console.log(err);
                tt.showToast({
                    title: '拉取失败,请重试',
                    icon: 'none',
                    duration: 1500,
                });
                game.resume();
                EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, false);
            });
            this.m_rewarded_video_ad.onClose((res) => {
                game.resume();
                // 用户点击了【关闭广告】按钮
                if (res && res.isEnded) {
                    console.log('长激励广告正常播放结束');
                    EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, true);
                } else {
                    console.log('长激励广告播放中途结束');
                    EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, false);
                }
            });
        }
    }
    public DestoryInterstitialAd() {
        console.log('消除插屏处理');
    }
    public ShowInterstitialAd() {
        if (this.m_cant_ad) {
            return;
        }
        if (this.m_platform_type == PlatformType.PLATFORM_TYPE_WEIXIN) {
            if (this.m_interstitial_ad == null) {
                console.log('插屏幕广告未创建');
                return;
            }
            this.m_interstitial_ad.show().catch((err) => {
                console.error(err);
            });
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_BYTEDACE) {
            if (this.m_interstitial_ad == null) {
                console.log('插屏幕广告未创建');
                return;
            }
            console.log('请求展示插屏广告');
            if (AdShowHelper.CanShow_AD) {
                console.log('可以直接调用展示插屏广告');
                this.m_interstitial_ad
                    .show()
                    .then(() => {
                        console.log('插屏广告展示成功');
                        AdShowHelper.SetAfterTimeToCanShowAD(60);
                        EventManagerInstance.GetInstance().Notify(GameMsgType.InterstADEndHanle, true);
                    })
                    .catch((err) => {
                        console.log('调用展示插屏广告失败');
                        console.error(this.SwitchShowErrCode(err.errCode));
                        AdShowHelper.SetAfterTimeToCanShowAD(60);
                        EventManagerInstance.GetInstance().Notify(GameMsgType.InterstADEndHanle, false);
                    });
            } else {
                console.log('不可以直接调用展示插屏广告 time no in');
            }
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_IOS) {
            console.log('send to ios ');
            // jsb.reflection.callStaticMethod('CocosPlatformHelper', 'ShowInsertAD', '()V');
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_ANDROID) {
            if (!AdShowHelper.CanShow_AD) return;
            AdShowHelper.SetAfterTimeToCanShowAD(60);
            console.log('send to android ');
            this.m_interstitial_ad = new InterstitialAdClient();

            this.m_interstitial_ad.load(GoogleAdmobUnitId.InterstitialAd, {
                onAdLoaded: () => {
                    log(interstmodule, 'onAdLoaded');
                    console.log('onAdLoaded will show');
                    this.m_interstitial_ad.show();
                },
                onAdFailedToLoad: (loadAdError) => {
                    log(interstmodule, 'onAdFailedToLoad, error: ', loadAdError);
                    console.log('onAdFailedToLoad will destroy');
                    this.m_interstitial_ad.destroy();
                },

                onPaidEvent(paidNTF: InterstitialPaidEventNTF) {
                    // paid event, you can do your own analysis here.
                    log(interstmodule, 'onPaidEvent', paidNTF);
                },
            });
        }
    }
    public ShowRewardAD(typename: string = null) {
        if (this.m_platform_type == PlatformType.PLATFORM_TYPE_WEIXIN) {
            if (!this.m_reward_ad_use) {
                return;
            }
            if (this.m_rewarded_video_ad == null) {
                console.log('激励广告未创建');
                EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADError, 'no create');
                return;
            }
            // 用户触发广告后，显示激励视频广告
            this.m_rewarded_video_ad.show().catch(() => {
                // 失败重试
                this.m_rewarded_video_ad
                    .load()
                    .then(() => this.m_rewarded_video_ad.show())
                    .catch((err) => {
                        console.log(err);
                        console.log('激励视频 广告显示拉取失败');
                        wx.showToast({
                            title: '激励视频拉取失败,请稍后重试',
                            icon: 'none',
                            duration: 2000,
                        });
                        EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADError, err);
                    });
            });
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_BYTEDACE) {
            if (game.isPaused()) return;

            game.pause();
            if (this.m_rewarded_video_ad == null) {
                game.resume();
                console.log('激励广告未创建');
                EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADError, '广告创建失败');
                EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, false);
                return;
            }
            // 用户触发广告后，显示激励视频广告
            this.m_rewarded_video_ad.show().catch(() => {
                // 失败重试
                this.m_rewarded_video_ad
                    .load()
                    .then(() => this.m_rewarded_video_ad.show())
                    .catch((err) => {
                        game.resume();
                        console.log(err);
                        console.log('激励视频 广告显示拉取失败');
                        // EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADError, err);
                        EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, false);
                    });
            });
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_IOS) {
            console.log('send to ios ');
            //jsb.reflection.callStaticMethod('CocosPlatformHelper', 'ShowRewardAD', '()V');
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_ANDROID) {
            console.log('send to android ');
            if (game.isPaused()) return;
            game.pause();
            //jsb.reflection.callStaticMethod('org/cocos2dx/javascript/CocosPlatformHelper', 'ShowRewardAD', '()V');
            this.m_rewarded_video_ad = new RewardedAdClient();

            this.m_rewarded_video_ad.load(GoogleAdmobUnitId.RewardedAd, {
                onAdLoaded: () => {
                    console.log('onAdLoaded');
                    log(rewardmodule, 'onClickLoadRewardedAd', 'onAdLoaded');
                    this.m_rewarded_video_ad.show();
                },
                onAdFailedToLoad: (loadAdError) => {
                    console.log('onAdFailedToLoad');
                    game.resume();
                    log(rewardmodule, 'onClickLoadRewardedAd', 'onAdFailedToLoad', loadAdError);
                    EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, false);
                },
                onEarn: (rewardType, amount) => {
                    console.log('onEarn');
                    // log(rewardmodule, 'onClickLoadRewardedAd', `onEarn, rewardType = ${rewardType}, amount = ${amount}`);
                    this.m_google_ad_rewarded = true;
                },
                onAdDismissedFullScreenContent: () => {
                    console.log('onAdDismissedFullScreenContent');
                    game.resume();
                    log(rewardmodule, 'onAdDismissedFullScreenContent');
                    this.m_rewarded_video_ad.destroy();
                    EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, this.m_google_ad_rewarded);
                    this.m_google_ad_rewarded = false;
                },
                onAdFailedToShowFullScreenContent: (adError) => {
                    log(rewardmodule, 'onAdFailedToShowFullScreenContent, adError: ', adError);
                    this.m_rewarded_video_ad.destroy();
                    EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, false);
                },
                onPaidEvent(paidNTF) {
                    log(module, 'onPaidEvent', paidNTF);
                },
            });
        } else {
            EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, true);
        }
    }

    public ShowBannerAD() {
        if (this.m_cant_ad) {
            return;
        }
        console.log('show banner ad');
        if (this.m_platform_type == PlatformType.PLATFORM_TYPE_WEIXIN) {
            this.m_banner_ad.show();
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_BYTEDACE) {
            this.m_banner_ad
                .show()
                .then(() => {
                    console.log('Banner广告展示成功');
                })
                .catch((err) => {
                    console.log('Banner广告展示失败');
                    console.error(this.SwitchShowErrCode(err.errCode));
                });
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_IOS) {
            console.log('send to ios ');
            //jsb.reflection.callStaticMethod('CocosPlatformHelper', 'ShowBannerAD', '()V');
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_ANDROID) {
            console.log('send to android ');
            this.m_android_banner_visible = true;
            if (this.m_banner_ad != null && this.m_android_banner_loaded) {
                this.m_banner_ad.show(this.m_android_banner_visible);
                return;
            }
            this.m_banner_ad = new BannerClient();
            this.m_banner_ad.load(
                GoogleAdmobUnitId.BannerAd,
                {
                    onAdImpression: () => {
                        console.log('onAdImpression');
                        log(bannermodule, 'onAdImpression', 'onAdImpression', this);
                    },

                    onAdClicked: () => {
                        console.log('onAdClicked');
                        log(bannermodule, 'onClickLoadBanner', 'onAdClicked');
                    },

                    onAdLoaded: () => {
                        console.log('onAdLoaded');
                        log(bannermodule, 'onClickLoadBanner', 'onAdLoaded');
                        this.m_android_banner_loaded = true;
                        this.m_banner_ad.show(this.m_android_banner_visible);
                    },

                    onAdFailedToLoad: (loadError: LoadAdError) => {
                        console.log('onAdFailedToLoad');
                        log(bannermodule, 'onClickLoadBanner', 'onFailedToLoad', `${loadError}`);
                    },

                    onPaidEvent(paidNTF: BannerPaidEventNTF) {
                        console.log('onPaidEvent');
                        // paid event, you can do your own analysis here.
                        log(bannermodule, 'onPaidEvent', paidNTF);
                    },
                },
                // { alignments: this.currentAlignment, type: BannerSizeType.Portrait }
                { size: BannerSize.FULL_BANNER, alignments: BottomCenter }
            );
        }
    }
    public HideBannerAD() {
        if (this.m_cant_ad) {
            return;
        }
        console.log('hide banner ad');
        if (this.m_platform_type == PlatformType.PLATFORM_TYPE_WEIXIN) {
            this.m_banner_ad.hide();
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_BYTEDACE) {
            this.m_banner_ad.hide();
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_IOS) {
            console.log('send to ios ');
            //jsb.reflection.callStaticMethod('CocosPlatformHelper', 'HideBannerAD', '()V');
        } else if (this.m_platform_type == PlatformType.PLATFORM_TYPE_ANDROID) {
            console.log('send to android hide banner ');
            if (this.m_banner_ad != null) {
                this.m_android_banner_visible = false;
                if (this.m_android_banner_loaded) {
                    this.m_banner_ad.show(this.m_android_banner_visible);
                }
            }
        }
    }
    public SwitchShowErrCode(errCode) {
        switch (errCode) {
            case 1001:
                return 'videoId 类型不正确';
            case 1002:
                return ' 视频已经被删除';
            case 1003:
                return 'videoId 不正确';
            case 1004:
                return '获取视频信息错误';
            case 1005:
                return '其他错误';
            case 1006:
                return '网络错误';
            case 1007:
                return '端上其他错误';
            case 1008:
                return '端上参数错误';
            case 2001:
                return '小程序启动一定时间内不允许展示插屏广告';
            case 2002:
                return '距离小程序插屏广告或者激励视频广告上次播放时间间隔不足，不允许展示插屏广告';
            case 2003:
                return '当前正在播放激励视频广告或者插屏广告，不允许再次展示插屏广告';
            case 2004:
                return '该项错误不是开发者的异常情况，或因小程序页面切换导致广告渲染失败';
            case 2005:
                return '插屏广告实例不允许跨页面调用';
            default:
                return '未知的其他错误';
        }
    }
    //原生处理激励广告回调
    public RewardADCallBack(sucess) {
        if (this.m_platform_type == PlatformType.PLATFORM_TYPE_IOS || this.m_platform_type == PlatformType.PLATFORM_TYPE_ANDROID) {
            if (sucess) {
                EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, true);
            } else {
                EventManagerInstance.GetInstance().Notify(GameMsgType.RewardADEnd, false);
            }
        }
    }
}
